package com.cskaoyan._02sync;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/22 10:52
 **/
/*
同步方法的锁对象---->this
 */
public class Demo2 {
    public static void main(String[] args) {
        SellWindow2 sellWindow = new SellWindow2();
        new Thread(sellWindow, "A窗口").start();
        new Thread(sellWindow, "B窗口").start();
        new Thread(sellWindow, "C窗口").start();
    }
}

class SellWindow2 implements Runnable {

    int tickets = 100;

    // 定义一把锁
    //Object lock = new Object();
    //C lock = new C();
    int i = 0;

    @Override
    public void run() {
        while (true) {

            if (i % 2 == 0) {
                // 使用同步代码块
                synchronized (this) {
                    if (tickets > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        System.out.println(Thread.currentThread().getName() + "卖了第"
                                + (tickets--) + "张票");
                    }
                }
            } else {

                sell();

            }
            i++;


        }
    }

    private synchronized void sell() {

        if (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName() + "卖了第"
                    + (tickets--) + "张票");
        }
    }

}

class C{}